﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Yeap.Kernel.Security;
using Yeap.Kernel.Storage;

namespace Yeap.Models
{
    public class WidgetColumns
    {
        private int columnCount = 2;
        private List<List<WidgetInformation>> columns;

        private bool initialized = false;

        private void LoadWidgets()
        {
            if (columns != null)
            {
                columns.Clear();    
            }
            else
            {
                columns = new List<List<WidgetInformation>>();
            }
            
            for (int i = 0; i < columnCount; i++)
            {
                var column = new List<WidgetInformation>();
                column.AddRange( LoginUtils.CurrentUser.UserWidget
                                    .Where(uw => uw.ColumnNumber == i)
                                    .OrderBy(uw => uw.ColumnOrder)
                                    .Select(uw => new WidgetInformation(uw.Widget))
                                    .ToList());
                
                columns.Add(column);
            }
            initialized = true;
        }

        public String GetStyleAttribute(int position)
        {
            return String.Format("style=width:{0}%;", GetWidthOfTheColumn(position));
        }

        public String GetWidthOfTheColumn (int position)
        {
            return LoginUtils.CurrentUser.HomePageLayout.LayoutRecord.Split(new char[] {','}, StringSplitOptions.RemoveEmptyEntries).ElementAt(position);
        }

        public Int32 ColumnCount
        {
            get { return columnCount; }
            set { columnCount = value; }
        }
        
        public List<List<WidgetInformation>> Columns
        {
            get
            {
                if (!initialized)
                {
                    LoadWidgets();
                }
                return columns;
            }
        }
    }

    public class WidgetInformation
    {
        public String WidgetName { get; set; }
        public String WidgetUserFriendlyName { get; set; }

        public Dictionary<string, object> Parameters { get; set; }

        public WidgetInformation(Widget widget )
        {
            if (widget == null)
            {
                throw new Exception("Database is inconsistent state.");
            }
            WidgetName = String.IsNullOrEmpty(widget.WidgetName) ? String.Empty : widget.WidgetName;
            WidgetUserFriendlyName = String.IsNullOrWhiteSpace(widget.HumanFriendly) ? WidgetName : String.Empty;
            Parameters = new Dictionary<string, object>();
        }
    }
}